package com.jams.goodox.activity.serve;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.text.Html;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.hangzhou.jin.customview.TextMoreLayout;
import com.jams.goodox.BaseActivity;
import com.jams.goodox.R;
import com.jams.goodox.SePref;
import com.jams.goodox.activity.home.HomeActivity;
import com.jams.goodox.activity.mine.address.MineAddressActivity;
import com.jams.goodox.constant.Constant;
import com.jams.goodox.entity.Address;
import com.jams.goodox.entity.ComplaintPriseBean;
import com.jams.goodox.entity.OrderCommitBean;
import com.jams.goodox.entity.ServeSubmitBean;
import com.jams.goodox.entity.ServicePeriod;
import com.jams.goodox.entity.User;
import com.jams.goodox.net.BaseEntity;
import com.jams.goodox.net.RetrofitCallbackListener;
import com.jams.goodox.net.services.ServiceService;
import com.jams.goodox.utils.DataCacheManager;
import com.jams.goodox.utils.ImageUtils;
import com.jams.goodox.utils.StyleUtil;
import com.jams.goodox.utils.ToastUtil;
import com.jams.goodox.utils.UImageUtils;
import com.jams.goodox.utils.Utils;
import com.jams.goodox.widget.ChooseBillView;
import com.jams.goodox.widget.DateTimePickerDialog;
import com.jams.goodox.widget.NoScrollGridView;
import com.jams.library.commonAdapter.ListCommonAdapter;
import com.jams.library.commonAdapter.ListCommonViewHolder;
import com.jams.library.utils.UniversalDeviceUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;

/**
 * 确认订单页
 * Created by jams_zhen on 2016/9/20.
 */

public class ServeSureOrderActivity extends BaseActivity {
    @Bind(R.id.tx_userName)
    TextView txUserName;
    @Bind(R.id.tx_userTel)
    TextView txUserTel;
    @Bind(R.id.tx_address)
    TextView txAddress;
    @Bind(R.id.tx_serveType)
    TextView txServeType;
    @Bind(R.id.tx_explainMsg)
    TextView txExplainMsg;
    @Bind(R.id.tx_serviceTime)
    TextMoreLayout txServiceTime;
    @Bind(R.id.grid_pic)
    NoScrollGridView gridView;
    @Bind(R.id.tx_company)
    TextView tx_company;
    @Bind(R.id.serve_include_address_user)
    LinearLayout serve_include_address_user;
    @Bind(R.id.order_include_user_address)
    LinearLayout order_include_user_address;
    @Bind(R.id.order_sure_name)
    TextView orderSureName;
    @Bind(R.id.order_sure_phone)
    TextView orderSurePhone;
    @Bind(R.id.address)
    TextView address;
    @Bind(R.id.choose_bill_view)
    ChooseBillView chooseBillView;

    private List<String> photos;
    private String serviceDay;
    private String serviceTime;

    private int type;

    private List<String> dateList;
    private List<String> timeZeroList;
    private List<String> timeNormalList;

    private DateTimePickerDialog dateTimePickerDialog;

    private String subjectId = "";
    private int orderNumber;

    private List<String> userIds;

    private int isOpenServiceTime = 1;

    private String explainMsg;
    private ServeSubmitBean serveSubmitBean;

    private User user;
    private Address userAddress;
    private boolean isPersonReport;
    private ChooseBillManager chooseBillManager;

    public static void go(Context context, ServeSubmitBean serveSubmitBean, boolean isPersonReport) {
        Intent in = new Intent(context, ServeSureOrderActivity.class);
        in.putExtra("serveSubmitBean", serveSubmitBean);
        in.putExtra("isPersonReport", isPersonReport);
        context.startActivity(in);
    }

    public static void go(Context context, ServeSubmitBean serveSubmitBean) {
        Intent in = new Intent(context, ServeSureOrderActivity.class);
        in.putExtra("serveSubmitBean", serveSubmitBean);
        context.startActivity(in);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.serve_sure_order_activity;
    }

    @Override
    protected void init() {
        StyleUtil.titleBackKey(this, "确认订单");
        serveSubmitBean = (ServeSubmitBean) getIntent().getSerializableExtra("serveSubmitBean");

        type = serveSubmitBean.getType();//大模块
        serviceDay = serveSubmitBean.getServiceDay();//服务日期
        serviceTime = serveSubmitBean.getServiceTime();//服务时间
        subjectId = serveSubmitBean.getSubId();//服务id
        isPersonReport = getIntent().getBooleanExtra("isPersonReport", false);//此值标识是否是个人报事
        user = DataCacheManager.getInstance().getUser();
//
        if (!TextUtils.isEmpty(serviceDay))
            isOpenServiceTime = 0;
        userIds = new ArrayList<>();
//
        if (TextUtils.isEmpty(serviceDay) || TextUtils.isEmpty(serviceTime)) {
            txServiceTime.setVisibility(View.GONE);
        } else {
            txServiceTime.setVisibility(View.VISIBLE);
            txServiceTime.setRightText(serviceDay + " " + serviceTime);
        }
        initBill();
        setUserInfo();
        setType();
        setCommentData();
    }

    /**
     * 处理发票
     */
    private void initBill(){
        if(serveSubmitBean.getType()== Constant.SERVE_TYPE_COMPANY){
            chooseBillManager = new ChooseBillManager(this, true, serveSubmitBean.getBusId(),chooseBillView);
        }
    }

    //此处设置中间部分，标题，备注和图片信息
    private void setCommentData(){
        userIds = new ArrayList<>();
        ArrayList<ComplaintPriseBean> complaintPriseBeanArrayList = serveSubmitBean.getComplaintPriseBeanArrayList();//用户id数组
        String itemName=serveSubmitBean.getItemName();
        if(complaintPriseBeanArrayList!=null&&complaintPriseBeanArrayList.size()>0){//投诉表扬且非其他，此时显示标题，提交数据需要修改
            String userPJ = "";
            for (int i = 0, len = complaintPriseBeanArrayList.size(); i < len; i++) {
                if (complaintPriseBeanArrayList.get(i).isChoose()) {//有选择项
                    ComplaintPriseBean complaintPriseBean = complaintPriseBeanArrayList.get(i);
                    userIds.add(complaintPriseBean.getUserId());
                    if (TextUtils.isEmpty(userPJ)) {
                        userPJ = userPJ + complaintPriseBean.getUserName();
                    } else {
                        userPJ = userPJ + "、" + complaintPriseBean.getUserName();
                    }
                }
            }
            if (userIds.size() == 0) {//无选择项时
                userIds.add(complaintPriseBeanArrayList.get(0).getUserId());
                userPJ = complaintPriseBeanArrayList.get(0).getUserName();
            }
            itemName = itemName + "-" + userPJ;
        }
        explainMsg = String.format("#%s#%s", itemName, serveSubmitBean.getMsg());
        Spanned spanned = Html.fromHtml(String.format("<font color=%s>", getString(R.string.main_theme_string))
                + String.format("#%s#", itemName) + "</font>"
                + "<font color=#333333>" +  serveSubmitBean.getMsg() + "</font>");
        txExplainMsg.setText(spanned);//子标题+备注
        txServeType.setText(serveSubmitBean.getTitle());//中部标题
        photos = serveSubmitBean.getPhotos();//图片列表
        setAdapter();
    }


    @OnClick({R.id.relative_address, R.id.tx_serviceTime, R.id.tx_submitOrder})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.relative_address:
                if(!isPersonReport)return;
                Intent in = new Intent(this, MineAddressActivity.class);
                if(!TextUtils.isEmpty(user.getAddress().getId()))in.putExtra("id", user.getAddress().getId());
                startActivityForResult(in, 122);
                break;
            case R.id.tx_serviceTime:
                getServiceDateTime();
                break;
            case R.id.tx_submitOrder:
                submitOrder();
                break;
        }
    }

    /**
     * 设置居家维修等等
     * 快递服务中为物品重量单位KG；叫车服务中为辆数，维修服务 1为公共维修 2为居家维修, 1投诉2表扬其他服务为空
     */
    private void setType() {
        switch (type) {
            case Constant.SERVE_TYPE_COMPANY:
                orderNumber = 2;
                break;
            case Constant.SERVE_TYPE_PUBLIC:
                orderNumber = 1;
                break;
            case Constant.SERVE_TYPE_REPORT:
                break;
            case Constant.SERVE_TYPE_COMPLAINT:
                orderNumber = 1;
                break;
            case Constant.SERVE_TYPE_PRAISE:
                orderNumber = 2;
                break;
            case Constant.SERVE_TYPE_EXPRESS:
                break;
            default:
                break;
        }
    }

    /**
     * 設置girdview適配器
     */
    private void setAdapter() {
        if (photos == null || photos.size() == 0) {
            gridView.setVisibility(View.GONE);
        } else {
            ListCommonAdapter commonAdapter = new ListCommonAdapter<String>(this, photos, R.layout.item_serve_image) {
                @Override
                public void convert(ListCommonViewHolder helper, String item, int position) {
                    ImageView img_serve = helper.getView(R.id.img_serve);
                    int lan = (UniversalDeviceUtils.getDisplayWidth(ServeSureOrderActivity.this) - Utils.dp2px(ServeSureOrderActivity.this, 54)) / 4;
                    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, lan);
                    img_serve.setLayoutParams(layoutParams);
                    img_serve.setImageBitmap(ImageUtils.getImage(item));
                }
            };
            gridView.setAdapter(commonAdapter);
        }
    }

    /**
     * 获取服务时间
     */
    private void getServiceDateTime() {
        enqueue(createCallService(ServiceService.class).getServicePeriod(subjectId), new RetrofitCallbackListener<ServicePeriod>() {
            @Override
            public void onSuccess(Call<ServicePeriod> call, ServicePeriod servicePeriod) {
                if (servicePeriod.getData() == null) return;
                dateList = servicePeriod.getData().getDays();
                timeZeroList = servicePeriod.getData().getTimeZero();
                timeNormalList = servicePeriod.getData().getTimeNormal();
                if (servicePeriod.getData().getIsOpenTime() != 0) return;
                showNumPicker();
            }

            @Override
            public void onError(String msg) {
                ToastUtil.show(msg);
            }
        });
    }

    /**
     * 弹出服务时间框
     */
    private void showNumPicker() {
        if (dateTimePickerDialog == null) {
            dateTimePickerDialog = new DateTimePickerDialog(this, dateList, timeZeroList, timeNormalList);
            dateTimePickerDialog.setOnDateTimeSetListener(new DateTimePickerDialog.OnDateTimeSetListener() {
                @Override
                public void OnDateTimeSet(AlertDialog dialog, String date, String hours) {
                    serviceDay = date;
                    serviceTime = hours;
                    txServiceTime.setRightText(serviceDay + " " + serviceTime);
                    dialog.cancel();
                }
            });
            dateTimePickerDialog.setDateTime(serviceDay, serviceTime);
        }
        dateTimePickerDialog.show();
    }

    /**
     * 设置用户名，手机号，地址:此处将个人报事也同步在此处理
     */
    private void setUserInfo() {
        //来自个人报事：显示下订单的个人和地址；来自企业服务：显示企业关联人相关信息
        if (isPersonReport) {
            order_include_user_address.setVisibility(View.VISIBLE);
            serve_include_address_user.setVisibility(View.GONE);

            orderSureName.setText(user.getUserName());
            orderSurePhone.setText(user.getMobileNum());
            userAddress = user.getAddress();
            address.setText(!User.isAddressExit(userAddress) ? "" : userAddress.getAddressDetail());

        } else {
            order_include_user_address.setVisibility(View.GONE);
            serve_include_address_user.setVisibility(View.VISIBLE);

            txUserName.setText(user.getUserName());
            txUserTel.setText(user.getMobileNum());
            txAddress.setText(user.getEnterpriseAddress());
            tx_company.setText(user.getEnterpriseName());
        }
    }

    /**
     * 提交订单
     */
    private void submitOrder() {
        if(isPersonReport&&!user.isUserAddressExit()){
            ToastUtil.show("请选择收货地址");
            return ;
        }
        showLoading();
        List<MultipartBody.Part> partList = new ArrayList<>();
        if (photos != null && photos.size() > 0) {
            for (String str : photos) {
                try {
                    File imgFile = UImageUtils.sword(str);
                    partList.add(MultipartBody.Part.createFormData("files", imgFile.getName(),
                            RequestBody.create(MediaType.parse("image/png"), imgFile)));
                }catch (Exception e){
                    e.printStackTrace();
                }

            }
        }
        enqueue(createCallService(ServiceService.class).submitOrder(createSuggestionJson(), partList), new RetrofitCallbackListener<BaseEntity>() {
            @Override
            public void onSuccess(Call<BaseEntity> call, BaseEntity servicePeriod) {
                ToastUtil.showShort(ServeSureOrderActivity.this, "提交成功");
                startActivity(new Intent(ServeSureOrderActivity.this, HomeActivity.class));
                finish();
                UImageUtils.deleteAllFiles(new File(UImageUtils.Path));
            }

            @Override
            public void onError(String msg) {
                misLoading();
                ToastUtil.show(msg);
            }
        });
    }

    //构建报事json
    private RequestBody createSuggestionJson() {
        OrderCommitBean orderCommitBean = new OrderCommitBean();

        if (User.isAddressExit(userAddress)) {
            orderCommitBean.setAddressId(userAddress.getId());
            orderCommitBean.setUserAddress(userAddress.getAddressDetail());
        }

        orderCommitBean.setCommunityId(SePref.getCommunityId());
        orderCommitBean.setEnterpriseHouseId(user.getEnterpriseHouseId());
        orderCommitBean.setEnterpriseId(user.getEnterpriseId());
        orderCommitBean.setEnterpriseName(user.getEnterpriseName());
        orderCommitBean.setEnterpriseAddress(user.getEnterpriseAddress());

        orderCommitBean.setIsOpenTime(isOpenServiceTime);
        orderCommitBean.setMoneyType(0);
        orderCommitBean.setOrderRemark(explainMsg);
        orderCommitBean.setOrderDate(serviceDay);
        orderCommitBean.setOrderTime(serviceTime);
        orderCommitBean.setRepairId(serveSubmitBean.getRepairId());
        orderCommitBean.setSubjectId(subjectId);
        orderCommitBean.setUserIds(userIds);//投诉表扬用户id列表，
        orderCommitBean.setOrderCreateClassfiy(isPersonReport?1:2);
        if (chooseBillManager!=null&&!"0".equalsIgnoreCase(chooseBillManager.getInvoiceType()))
            orderCommitBean.setInvoiceType(chooseBillManager.getInvoiceType());
        if (orderNumber != 0)
            orderCommitBean.setOrderNumber(orderNumber);
        if (!TextUtils.isEmpty(serveSubmitBean.getExpFirm()))
            orderCommitBean.setExpFirm(serveSubmitBean.getExpFirm());
        if (!TextUtils.isEmpty(serveSubmitBean.getExpNo()))
            orderCommitBean.setExpFirm(serveSubmitBean.getExpNo());
        String strJson = new Gson().toJson(orderCommitBean);
        return RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), strJson);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) return;
        if (resultCode == 1 && requestCode == 122) {//获取传递的地址
            userAddress = (Address) data.getSerializableExtra("bean");
            if (userAddress == null) return;
            address.setText(userAddress.getAddressDetail());
        }if(requestCode==1991){//重新获取发票信息
            chooseBillManager.getMyInvoice();
        }
    }
}
